import * as Less from 'less'
import { requireLocalPkg } from './requirePackage'

type LessType = typeof Less

/**
 * 尝试加载本地 node-less/less
 */
function autoRequireLess(file: string): LessType {
  try {
    return requireLocalPkg<LessType>(file, 'less')
  } catch (error) {
    return requireLocalPkg<LessType>(file, 'node-less')
  }
}

/**
 * 渲染less
 * @param file less文件路径
 * @param op less 配置
 */
export default function(file: string, content: string, op?: Less.Options): Promise<string> {
  // const content = readFileSync(file).toString();

  const options: Less.Options = {
    ...op,
    filename: file
  }

  return new Promise((resolve, reject) => {
    try {
      autoRequireLess(file || process.cwd())
        .render(content, options).then(resp => {
          resolve(resp.css)
        }).catch(error => {
          console.error(error)
          resolve(content);
        })
    } catch (error) {
      // less 渲染失败退回
      console.error(error)
      resolve(content)
    }
  })
  
}
